﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.AuthorCenter.ApiMetadatas.Repositories;
using mozhi.smarterp.AuthorCenter.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.AuthorCenter.ApiMetadatas
{
    public class ApiMetadataRepository : EfCoreRepository<AuthorCenterDbContext, ApiMetadata, Guid>, IApiMetadataRepository
    {
        public ApiMetadataRepository(IDbContextProvider<AuthorCenterDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<ApiMetadata> FindAsync(string path, string method, string apiScope, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var openApi = await dbContext.Set<ApiMetadata>().AsNoTracking()
                .Where( x => x.ApiScope == apiScope && x.Path == path && x.Method == method)
                .FirstOrDefaultAsync();

            return openApi;
        }

        public async Task<List<ApiMetadata>> GetListAsync(string apiScope, string path, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var openApis = await dbContext.Set<ApiMetadata>().AsNoTracking()
                .WhereIf(!apiScope.IsNullOrEmpty(), x => x.ApiScope == apiScope)
                .WhereIf(!path.IsNullOrEmpty(), x => x.Path == path)
                .ToListAsync();
                ;

            return openApis;
        }

        public async Task<List<ApiMetadata>> GetListAsync(List<Guid> ids, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var openApis = await dbContext.Set<ApiMetadata>().AsNoTracking()
                .Where(x => ids.Contains(x.Id))
                .ToListAsync();

            return openApis;
        }
    }
}
